package com.df.happylearn.model;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

@DatabaseTable(tableName = "table_article")
public class ArticleInfo {
    @DatabaseField(id = true, uniqueCombo = true, columnName = "articleId")
    public int mId; //id
    @DatabaseField(columnName = "catid")
    public int mCatId; //cat_id
    @DatabaseField(columnName = "viewname")
    public String mViewName; //view_name
    @DatabaseField(columnName = "title")
    public String mTitle; // title
    @DatabaseField(columnName = "ctime")
    public String mCtime; // time
    @DatabaseField(columnName = "thumbnail")
    public String mThumbnail; // head
    @DatabaseField(columnName = "original")
    public String mOriginal; //article source
    @DatabaseField(columnName = "isread")
    public int isread; // read state

    //json对象解析
    public static ArticleInfo parseJson(JSONObject jsonObject) {
        try {
            ArticleInfo item = new ArticleInfo();
            if (jsonObject.has("id")) {
                item.mId = Integer.parseInt(jsonObject.getString("id"));
            }
            if (jsonObject.has("cat_id")) {
                item.mCatId = Integer.parseInt(jsonObject.getString("cat_id"));
            }
            if (jsonObject.has("view_name")) {
                item.mViewName = jsonObject.getString("view_name");
            }
            if (jsonObject.has("title")) {
                item.mTitle = jsonObject.getString("title");
            }
            if (jsonObject.has("ctime")) {
                item.mCtime = jsonObject.getString("ctime");
            }
            if (jsonObject.has("thumbnail")) {
                item.mThumbnail = jsonObject.getString("thumbnail");
            }
            if (jsonObject.has("original")) {
                item.mOriginal = jsonObject.getString("original");
            }
            return item;
        } catch (Exception e) {
            return null;
        }
    }

    public static ArrayList<ArticleInfo> parseJsonArray(JSONArray jsonArray) {
        try {
            ArrayList<ArticleInfo> itemList = new ArrayList<>();
            for (int i = 0; i < jsonArray.length(); i++) {
                ArticleInfo item = ArticleInfo.parseJson(jsonArray.getJSONObject(i));
                if (item != null) {
                    itemList.add(item);
                }
            }
            return itemList;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }
}
